﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinHBM.Core.Net.Http
{
    public class DownloadRes
    {
        private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(DownloadRes));

        // "images/head/"+Utils.UtilMD5.encodeString(url) +".jpg"
        public static void downloadAsync(string url,string filePath, bool replace = false)
        {
            //判断，如果文件在本地已经存在，是否需要覆盖
            if (!replace)
            {
                if (File.Exists(filePath))
                {
                    return;
                }
            }
            string folder = filePath.Substring(0, filePath.LastIndexOf(@"\"));
            try
            {
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                WebClient client = new WebClient();
                Uri uri = new Uri(url);
                client.DownloadFileAsync(uri, filePath);
            }
            catch (Exception ex)
            {

                Logger.Debug(ex);
            }
            
        }

        public static void downloadSync(string url,string filePath,bool replace = false)
        {

            //判断，如果文件在本地已经存在，是否需要覆盖
            if (!replace)
            {
                if(File.Exists(filePath))
                {
                    return;
                }
            }


            string folder = filePath.Substring(0, filePath.LastIndexOf(@"\"));

            try {

                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                WebClient client = new WebClient();
                Uri uri = new Uri(url);
                client.DownloadFile(uri,filePath);
            }
            catch (Exception e) {
                //filePath = url;
                Logger.Debug(e);
            }

         
           
            //return filePath + filePath;
        }


    }
}
